package route

import (
	"fmt"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gview"
	"github.com/gogf/gf/v2/text/gstr"
)

type ChatExamplesMonitor struct {
}

type TestPage struct {
	Page    int `json:"page"`
	PerPage int `json:"perPage"`
}

const sqlTmp = `
select _t1.* from public.%s _t1 where _t1.time > now() - interval '%s' %s order by _t1.time desc
`

func (c *ChatExamplesMonitor) Monitor(r *ghttp.Request) {
	args, whereSql := processFilter(r)
	k := r.GetQuery("key")
	sql := fmt.Sprintf(sqlTmp, k, "30m", whereSql)
	db := g.DB("monitor")
	vs, err := db.GetAll(r.Context(), sql, args)
	if err != nil {
		panic(err)
	}
	r.Response.WriteJsonExit(map[string]interface{}{
		"rows": vs.List(),
	})
}

func (c *ChatExamplesMonitor) CustomSql(r *ghttp.Request) {
	k := r.GetQuery("key")
	var (
		req TestPage
	)
	r.GetQueryStruct(&req)
	qmap := r.GetQueryMap()
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PerPage <= 0 {
		req.PerPage = 10
	}
	sql, err := r.GetView().ParseOption(r.Context(), gview.Option{File: fmt.Sprintf("config/sqls/%s.sql", k), Orphan: true, Params: qmap})
	if err != nil {
		panic(err)
	}
	glog.Infof(r.GetCtx(), "模板sql: \n%s", sql)
	db := g.DB("monitor")
	vs, err := db.GetAll(r.Context(), fmt.Sprintf("select _t1.* from (%s) _t1 LIMIT %d OFFSET (%d - 1) * %d", sql, req.PerPage, req.Page, req.PerPage))
	if err != nil {
		panic(err)
	}
	cnt, err := db.GetCount(r.Context(), fmt.Sprintf("select count(1) from (%s) _t1", sql))
	if err != nil {
		panic(err)
	}
	r.Response.WriteJsonExit(map[string]interface{}{
		"count": cnt,
		"qmap":  qmap,
		"rows":  vs.List(),
	})
}

func processFilter(r *ghttp.Request) (args []interface{}, whereSql string) {
	args, whereSql = nil, ""
	param := map[string]interface{}{}
	gjson.DecodeTo(r.GetBodyString(), &param)
	for k, v := range param {
		fs := gstr.Split(k, "$$")
		if len(fs) == 2 {
			if fs[0] == "like" {
				whereSql += fmt.Sprintf(" and _t1.%s like ? ", fs[1])
				args = append(args, fmt.Sprintf("%%%s%%", v))
			}
		}
	}
	return args, whereSql
}
